<template>
    <div
        :class="['w-full text-20 p-24 box-border', { 'min-loading-height': isLoading }]"
        v-loading="isLoading"
        element-loading-text="加载中....."
    >
        <!-- 顶部 -->
        <PageHeader
            v-model="headerPopoverVisible"
            :operation-is-new-line="false"
            :is-need-screen='true'
            title="商品列表"
            :is-data-loading="isLoading"
            @refresh="resetList"
            @search="search"
        >
            <SearchBox type='left' title="商品名称">
                <el-input v-model="searchParams.goodsName" placeholder="请输入商品名称" />
            </SearchBox>
            <SearchBox type='right' title="商品编码">
                <el-input v-model="searchParams.goodsCode" placeholder="请输入商品编码" />
            </SearchBox>
            <SearchBox type='right' title="商品分类">
                <el-select
                    v-model="searchParams.goodsClassId"
                    class="w-full"
                    placeholder="请选择商品分类"
                    :teleported="false"
                >
                    <el-option
                        v-for="item in goodsClassList"
                        :key="item.goodsClassId"
                        :label="item.goodsClassName"
                        :value="item.goodsClassId"
                        @click.native.stop
                    />
                </el-select>
            </SearchBox>
            <template #custom>
                <el-button type="primary" round @click="toPage('add')">
                    <Icon name="Plus" class="mr-6"/>新增商品
                </el-button>
                <el-button round type="primary" @click="goodsClassDialogVisible = true">商品分类管理</el-button>
            </template>
        </PageHeader>
        <template v-if="!isLoading">
            <!-- 商品列表 -->
            <template v-if="goodList.length">
                <div class="w-full flex-between-items-box flex-wrap">
                    <div
                        class="goods-container card-style mb-20 flex-between-items-box common-shadow"
                        v-for="(item, index) in goodList"
                        :key="index"
                    >
                        <GoodDetail @updateGoodList="updateGoodList" :good-detail="item"/>
                    </div>
                    <!-- 分页 -->
                    <div class="flex-center-box w-full mt-20">
                        <el-pagination
                            v-model:current-page="pageParams.currentPage"
                            background
                            layout="total, prev, pager, next, jumper"
                            :total="pageParams.total"
                            @current-change="handleCurrentChange"
                        />
                    </div>
                </div>
            </template>
            <!-- 内容 -->
            <Empty v-else/>
        </template>
        <!-- 商品类型管理 -->
        <el-dialog
            v-model="goodsClassDialogVisible"
            title="商品分类管理"
            width="25%"
            top="300px"
            :before-close="handleClose"
        >
            <div class="flex">
                <el-input placeholder="请输入商品类型" v-model="goodsClassValue" clearable/>
                <el-button
                    round
                    class="ml-12"
                    type="primary"
                    @click="addGoodsClass"
                >
                    添加商品类型
                </el-button>
            </div>
            <!-- 已有商品类型 -->
            <template v-if="goodsClassList.length">
                <div class="pb-16">
                    <div class="w-full mt-20 mb-20 text-t-title">已有商品类型:</div>
                    <el-tag
                        v-for="item in goodsClassList"
                        :key="item.goodsClassId"
                        class="mb-14 mr-10"
                        closable
                        size="large"
                        round
                        type="success"
                        @change="deleteGoodsClass"
                        @close="deleteGoodsClass(item.goodsClassId)"
                    >
                        {{ item.goodsClassName }}
                    </el-tag>
                    <div class="mt-10">
                        <el-alert
                            type="warning"
                            show-icon
                            title="注意：若分类下存在商品将无法删除分类！"
                            :closable="false"
                        />
                    </div>
                </div>
            </template>
            <template v-else>
                <div class="pb-16 mt-20">暂无商品类型 ~</div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { PageParams, PageTypeKey } from '@/type/common'
import {
    GoodDetailData,
    GoodsClass,
    GoodsDetailResultData,
    GoodsListSearchParams,
    httpAddGoodsClass,
    httpDeleteGoodsClass,
    httpGoodsClassList,
    httpGoodsList
} from '@/api/module/goodsCenter'
import { ElMessages, timeout } from '@utils/methods'

// 组件
import PageHeader from '@/components/PageHeader/index.vue'
import SearchBox from '@/components/SearchBox/index.vue'
import Empty from '@/components/Empty/index.vue'
import Icon from '@components/Icon/index.vue'
import GoodDetail from './components/GoodDetail/index.vue'

const router = useRouter()

// 数据是否加载中
const isLoading = ref(true)

// 检索框状态
const headerPopoverVisible = ref(false)

// 获取商品分类列表
const getGoodsClassList = (type: 'default' | 'init' = 'default') => {
    // 获取商品分类列表
    httpGoodsClassList().then(({ success, data }) => {
        if (success) {
            goodsClassList.value = data ? data.list : []
            if (type === 'init') getGoodsList()
        }
    })
}

getGoodsClassList('init')

// 查询内容
const searchParams = reactive<GoodsListSearchParams>({
    goodsName: '',
    goodsCode: '',
    goodsClassId: null
})

// 分页
const pageParams = reactive<PageParams>({
    currentPage: 1,
    currentSize: 10,
    total: 10
})

// 商品列表
const goodList = ref<GoodDetailData | GoodsDetailResultData[]>([])

/**
 * 获取商品列表
 * */
const getGoodsList = async () => {
    isLoading.value = true
    httpGoodsList({
        ...searchParams,
        ...pageParams
    }).then(res => {
        goodList.value = res.data ? res.data.list.map((item: any) => {
            item.goodsClassName = goodsClassList.value.find(classItem => classItem.goodsClassId === item.goodsClassId)!.goodsClassName
            return item
        }) : []
        pageParams.total = res.data.total
    }).finally(async () => {
        headerPopoverVisible.value = false
        await timeout(500)
        isLoading.value = false
    })
}

// 删除后刷新数据
const updateGoodList = () => {
    pageParams.currentPage = 1
    pageParams.currentSize = 10
    getGoodsList()
}

/**
 * 重置数据
 * */
const resetList = () => {
    searchParams.goodsName = ''
    searchParams.goodsCode = ''
    searchParams.goodsClassId = null
    updateGoodList()
}

/**
 * 查询数据
 * */
const search = () => {
    pageParams.currentPage = 1
    pageParams.currentSize = 10
    getGoodsList()
}

// 当前页码改变
const handleCurrentChange = () => {
    console.log('页码改变')
    console.log(pageParams)
}

// 添加商品
// const editGoods = () => {
//     router.push('/GoodsCenter/AddEditDetail')
// }

// 前往详情页
const toPage = (pageType: PageTypeKey) => {
    router.push({
        path: '/GoodsCenter/AddEditDetail',
        query: { pageType }
    })
}

/**
 * 商品类型管理
 * */
// 商品类型管理弹窗
const goodsClassDialogVisible = ref(false)

// 商品类型值
const goodsClassValue = ref('')

// 商品类型
const goodsClassList = ref<GoodsClass[]>([])

// 弹窗关闭回调
const handleClose = () => {
    goodsClassDialogVisible.value = false
    goodsClassValue.value = ''
}

// 添加商品类型
const addGoodsClass = () => {
    if (!goodsClassValue.value) {
        ElMessages.warning('商品类型不能为空！')
        return
    }
    // 判断商品类型是否已存在
    const isIdent = goodsClassList.value.find(item => item.goodsClassName === goodsClassValue.value)
    if (isIdent) {
        ElMessages.warning('该商品类型已存在！')
        return
    }
    httpAddGoodsClass({
        goodsClassName: goodsClassValue.value
    }).then(({ success }) => {
        if (success) {
            goodsClassValue.value = ''
            ElMessages.success('添加成功！')
            getGoodsClassList()
        } else {
            ElMessages.error('添加失败，请重试！')
        }
    })
}

// 删除商品类型
const deleteGoodsClass = (goodsClassId: number) => {
    httpDeleteGoodsClass({ goodsClassId }).then(({ success, message }) => {
        if (success) {
            ElMessages.success('删除成功！')
            getGoodsClassList()
        } else {
            ElMessages.error(message!)
        }
    })
}
</script>

<style lang="less" scoped>
:deep(.el-range-editor.el-input__wrapper){
    width: 100% !important;
}

.goods-container{
    width: calc(50% - 10px);
    height: 180px;
    overflow: hidden;
    transition: all .3s;

    div:nth-child(2n) {
        @apply ml-20;
    }
}

.goods-container:hover{
    transform: scale(1.02);
}

:deep(.el-pager .number){
    border-radius: 8px !important;
}
</style>
